package hichecker.ui.custom_views.series;

import hichecker.controller.Config;
import hichecker.controller.MainController;
import hichecker.tools.export.CSVFile;
import hichecker.ui.components.custom_table.CustomTable;
import hichecker.ui.components.icon_factory.IconFactory;
import hichecker.ui.general_views.container_panel.content.ContentPanel;
import hichecker.university.Series;
import hichecker.university.Student;
import hichecker.university.UniversityPart;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;

import org.apache.log4j.Logger;

public class SeriesView extends ContentPanel {
	private Logger logger = Logger.getLogger(SeriesView.class);
	private MainController controller;
	private Series series;
	private List<Student> students;

	private SeriesViewTableModel model;
	private CustomTable tblSeries;
	private JButton btnGroup;
	private JButton btnClearGroup;

	public SeriesView(UniversityPart item, MainController controller) {
		super(item);

		if (!(item instanceof Series)) {
			logger.error("Parameter is not a series!");
			return;
		}
		series = (Series) item;
		this.students = controller.getStudents();
		this.controller = controller;

		initComponents();
	}

	/**
	 * Inits the GUI components
	 */
	private void initComponents() {

		// Table, model and the pane
		model = new SeriesViewTableModel(students, series);
		tblSeries = new CustomTable(model, getWidth());
		JScrollPane pane = new JScrollPane(tblSeries);

		// Register key events for grouping and resetting
		tblSeries.getInputMap().put(Config.HOTKEY_GROUP, "group");
		tblSeries.getActionMap().put("group", new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				groupStudents();
			}
		});
		tblSeries.getInputMap().put(Config.HOTKEY_GROUP_CLEAR, "clear");
		tblSeries.getActionMap().put("clear", new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				clearGrouping();
			}
		});

		// Button for grouping students
		btnGroup = IconFactory.getIconButton(Config.BUTTON_GROUP, null, null, new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				groupStudents();
			}
		});

		// Button for disabling grouping
		btnClearGroup = IconFactory.getIconButton(Config.BUTTON_GROUP_CLEAR, null, null, new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				clearGrouping();
			}
		});

		JButton btnDelete = IconFactory.getIconButton(Config.BUTTON_REMOVE, null, null, new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				deleteLines();
			}
		});
		tblSeries.getInputMap().put(Config.HOTKEY_DELETE, "delete");
		tblSeries.getActionMap().put("delete", new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				deleteLines();
			}
		});

		// Layout
		GroupLayout layout = new GroupLayout(this);
		setLayout(layout);

		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);

		// Horizontal Layout
		layout.setHorizontalGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup()
						.addComponent(pane)
						.addGroup(layout.createSequentialGroup()
								.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(btnGroup)
								.addComponent(btnClearGroup)
								.addComponent(btnDelete)
						)
				)
		);

		// Vertical Layout
		layout.setVerticalGroup(layout.createSequentialGroup()
				.addComponent(pane)
				.addGroup(layout.createParallelGroup()
						.addComponent(btnGroup)
						.addComponent(btnClearGroup)
						.addComponent(btnDelete)
				)
		);
		setVisible(true);
	}

	private void deleteLines() {
		// No line selected
		if (tblSeries.getSelectedRow() < 0) return;
		if (!userConfirmed()) return;

		int[] selectedRows = tblSeries.getSelectedModelRows();
		for (int i = selectedRows.length - 1; i >= 0; i--)
			model.deleteRow(selectedRows[i]);
	}

	/**
	 * Groups all selected students as one student
	 */
	private void groupStudents() {
		if (tblSeries.getSelectedRowCount() <= 0)
			return;

		int selRow = tblSeries.getSelectedRow();
		int selCol = tblSeries.getSelectedColumn();
		model.setGrouping(tblSeries.getSelectedModelRows());
		tblSeries.changeSelection(selRow, selCol, false, false);
	}

	@Override
	public boolean isCorrect() {
		boolean isCorrect = tblSeries.isCorrect();
		if (isCorrect) tblSeries.setCurrentValue();
		return isCorrect;
	}

	/**
	 * Clears the current grouping
	 */
	private void clearGrouping() {
		int selRow = tblSeries.getSelectedRow();
		int selCol = tblSeries.getSelectedColumn();
		model.clearGrouping();
		tblSeries.changeSelection(selRow, selCol, false, false);
	}

	@Override
	public void paint(Graphics g) {
		tblSeries.setAutoResizeable(getWidth());
		super.paint(g);
	}

	@Override
	public ContentPanel switchViewSettings() {
		return new SeriesSettings(series, controller);
	}

	@Override
	public List<CSVFile> toCSV(String topLevel) {
		String name = topLevel + " - " + item.getName();

		List<CSVFile> files = new ArrayList<CSVFile>();
		files.add(model.toCSV(name));

		return files;
	}
}
